/**
 * 二、基于以下代码完成下面的四个练习
 */
const fp = require('lodash/fp')
const { flowRight, get } = require('lodash')
const cars = [
  {
    name: 'Ferrari FF', horsepower: 660,
    dollar_value: 700000, in_stock: true
  },
  {
    name: 'Spyker C12 Zagato',
    horsepower: 650, dollar_value: 648000,
    in_stock: false
  },
  {
    name: 'Jaguar XKR-S', horsepower:
      550, dollar_value: 132000, in_stock:
      false
  },
  {
    name: 'Audi R8', horsepower: 525,
    dollar_value: 114200, in_stock: false
  },
  {
    name: 'Aston Martin One-77 ',
    horsepower: 750, dollar_value: 1850000,
    in_stock: true
  },
  {
    name: 'Pagani Huayra', horsepower:
      700, dollar_value: 1300000, in_stock:
      false
  },
]

// 练习 1: 使用函数组合 fp.flowRight ()重新实现下面这个函数
const getLastCar = (cars) => fp.last(cars)
const getInStock = (lastCar) => fp.prop('in_stock', lastCar)
const isLastlnStock = fp.flowRight(getInStock,getLastCar)
// console.log(isLastlnStock(cars)) // 执行结果 false

//练习 2 :使用 fp.flowRight() 、 fp.prop() 和 fp.first() 获取第一个 car 的 name
const getFirstCar = (cars) => fp.first(cars)
const getCarName = (car) => fp.prop('name', car)
const isFirstCarName = fp.flowRight(getCarName,getFirstCar)
// console.log(isFirstCarName(cars)) // 执行结果 Ferrari FF

// 练习 3: 使用帮助函数 _average 重构averageDollarValue ,使用函数组合的方式实现
let _average = function (xs) {
    return fp.reduce(fp.add, 0, xs) / xs.length
}
const log = (value) => {
    console.log(value)
    return value
}
const getDollarValue = (car) => car.dollar_value
const averageDollarValue = fp.flowRight(_average, fp.map(getDollarValue))
// console.log(averageDollarValue(cars)) // 执行结果 790700

//练习 4 :使用 flowRight  写一个 sanitizeNames ()函数，
//返回一个下划线连接的小写字符串，把数组中的 name 转换为这种形式：
//例如：sanitizeNames(["Hello World"]) => ["hello_world"]
let _underscore = fp.replace(/\W+/g, '_')
let getName = (car) => car.name
let setName = (car) => {
  getLowerName =  fp.flowRight(_underscore, fp.toLower, getName)
  car.name = getLowerName(car)
  return car
}
const sanitizeNames = fp.flowRight(fp.map(setName))
console.log(sanitizeNames(cars)) 
// 答案[
//   {
//     name: 'ferrari_ff',
//     horsepower: 660,
//     dollar_value: 700000,
//     in_stock: true
//   },...